package services

import (
	"time"

	"cashew.com/cashew_common/configs"
	"github.com/beego/beego/v2/core/logs"
)

func StartQuickCallTask() {
	anchorKeyPrefix := configs.TickerTaskAnchorKeyPrefix
	anchorNewKeyPrefix := configs.TickerTaskAnchorNewKeyPrefix
	tickerTaskTimerQuickCallSeconds := configs.TickerTaskTimerQuickCallSeconds

	ticker := time.NewTicker(time.Duration(tickerTaskTimerQuickCallSeconds) * time.Second)
	defer ticker.Stop()

	for {
		select {
		case <-ticker.C:
			// 执行任务
			logs.Info("执行定时匹配主播任务 %v", time.Now())

			// 删除过期用户并通知
			_ = cleanOldUsersAndNotice()

			// 1. 查询所有未匹配的主播 存入 redis 集合
			anchorOnlineList, err := GetOnlineTakingOrderAnchors()
			if err != nil {
				logs.Error("获取在线接单主播列表失败 %v", err)
				continue
			}

			if len(anchorOnlineList) == 0 {
				continue
			}

			// 2. 新的一轮，清除上一轮的新主播集合
			err = clearAnchorNewHashes()
			if err != nil {
				logs.Error("清除用户新哈希失败 %v", err)
				continue
			}

			// 3. 重新生成本轮新进主播集合
			err = UpdateAnchorHashes(anchorOnlineList, anchorKeyPrefix, anchorNewKeyPrefix)
			if err != nil {
				logs.Error("更新主播哈希失败 %v", err)
				continue
			}

			// 3. 匹配主播逻辑，只有有新进主播集合才进行匹配
			hashExists, _ := Redisserver.IsHashKeyExists(anchorNewKeyPrefix)
			if hashExists {
				userMatching()
			}
		}
	}
}
